{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "51411bb4",
   "metadata": {
    "colab_type": "text",
    "id": "view-in-github"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/peremartra/Large-Language-Model-Notebooks-Course/blob/main/1-Introduction%20to%20LLMs%20with%20OpenAI/1_1-First_Chatbot_OpenAI.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "zwzWskLgXgj5",
   "metadata": {
    "id": "zwzWskLgXgj5"
   },
   "source": [
    "<div>\n",
    "<h1>Large Language Models Projects</h1>\n",
    "    <h3>Apply and Implement Strategies for Large Language Models</h3>\n",
    "    <h2>1.1-Create your first Chatbot With OpenAI</h2>\n",
    "</div>\n",
    "\n",
    "by [Pere Martra](https://www.linkedin.com/in/pere-martra/)\n",
    "___________\n",
    "\n",
    "Models: gpt-3.5-turbo / gpt-4o-mini\n",
    "\n",
    "Colab Environment: CPU\n",
    "\n",
    "Keys:\n",
    "* OpenAI roles.\n",
    "* Memory in conversations.\n",
    "\n",
    "Related article: [Create Your First Chatbot Using GPT gpt-3.5-turbo / gpt-4o-mini, OpenAI, Python and Panel.](https://medium.com/towards-artificial-intelligence/create-your-first-chatbot-using-gpt-3-5-openai-python-and-panel-7ec180b9d7f2)\n",
    "___________________________\n",
    "\n",
    "This is the unofficial repository for the book:\n",
    "        <a href=\"https://amzn.to/4eanT1g\"> <b>Large Language Models:</b> Apply and Implement Strategies for Large Language Models</a> (Apress).\n",
    "        The book is based on the content of this repository, but the notebooks are being updated, and I am incorporating new examples and chapters.\n",
    "        If you are looking for the official repository for the book, with the original notebooks, you should visit the\n",
    "        <a href=\"https://github.com/Apress/Large-Language-Models-Projects\">Apress repository</a>, where you can find all the notebooks in their original format as they appear in the book."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c23b4dd1",
   "metadata": {
    "id": "c23b4dd1"
   },
   "source": [
    "# Vertical Chat\n",
    "How to build a chat for small businees using:\n",
    "\n",
    "* GPT 3.5 / GPT-4o mini\n",
    "* Panel\n",
    "* OpenAI\n",
    "\n",
    "\n",
    "This is just a simple sample to start understanding how the OpenAI API works, and how to create Prompts. It Is really far from beign a complete solution, but we are going to introduce some interesting points:\n",
    "\n",
    "* The roles in a conversation.\n",
    "* How is the conversations’ memory preserved?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1d00720",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "a1d00720",
    "outputId": "10c27673-9123-49b5-d4a6-f2761eda6f00"
   },
   "outputs": [],
   "source": [
    "#First install the necesary libraries\n",
    "!pip install -q openai==1.1.1\n",
    "!pip install -q panel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a03f026a",
   "metadata": {
    "id": "a03f026a"
   },
   "outputs": [],
   "source": [
    "#if you need a API Key from OpenAI\n",
    "#https://platform.openai.com/account/api-keys\n",
    "\n",
    "import openai\n",
    "import panel as pn\n",
    "openai.api_key=\"your-openai-key\"\n",
    "#model = \"gpt-3.5-turbo\"\n",
    "model = \"gpt-4o-mini\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77eac86d",
   "metadata": {
    "id": "77eac86d"
   },
   "outputs": [],
   "source": [
    "#This function will receive the different messages in the conversation,\n",
    "#and call OpenAI passing the full conversartion.\n",
    "def continue_conversation(messages, temperature=0):\n",
    "    response = openai.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature,\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "51bec475",
   "metadata": {
    "id": "51bec475"
   },
   "outputs": [],
   "source": [
    "def add_prompts_conversation(_):\n",
    "    #Get the value introduced by the user\n",
    "    prompt = client_prompt.value_input\n",
    "    client_prompt.value = ''\n",
    "\n",
    "    #Append to the context the User promnopt.\n",
    "    context.append({'role':'user', 'content':f\"{prompt}\"})\n",
    "\n",
    "    #Get the response.\n",
    "    response = continue_conversation(context)\n",
    "\n",
    "    #Add the response to the context.\n",
    "    context.append({'role':'assistant', 'content':f\"{response}\"})\n",
    "\n",
    "    #Update the panels to show the conversation.\n",
    "    panels.append(\n",
    "        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))\n",
    "    panels.append(\n",
    "        pn.Row('Assistant:', pn.pane.Markdown(response, width=600)))\n",
    "\n",
    "    return pn.Column(*panels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "922f8d24",
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 520
    },
    "id": "922f8d24",
    "outputId": "ac2023e3-5bfd-4160-8274-9ffa46d59e60"
   },
   "outputs": [],
   "source": [
    "#Creating the system part of the prompt\n",
    "#Read and understand it.\n",
    "\n",
    "context = [ {'role':'system', 'content':\"\"\"\n",
    "You work collecting orders in a delivery IceCream shop called\n",
    "I'm freezed.\n",
    "\n",
    "First welcome the customer, in a very friedly way, then collects the order.\n",
    "\n",
    "Your instuctions are:\n",
    "-Collect the entire order, only from options in our menu, toppings included.\n",
    "-Summarize it\n",
    "-check for a final time if everithing is ok or the customer wants to add anything else.\n",
    "-collect the payment, be sure to include topings and the size of the ice cream.\n",
    "-Make sure to clarify all options, extras and sizes to uniquely\n",
    "identify the item from the menu.\n",
    "-Your answer should be short in a very friendly style.\n",
    "\n",
    "Our Menu:\n",
    "The IceCream menu includes only the flavors:\n",
    "-Vainilla.\n",
    "-Chocolate.\n",
    "-Lemon.\n",
    "-Strawberry.\n",
    "-Coffe.\n",
    "\n",
    "The IceCreams are available in two sizes:\n",
    "-Big: 3$\n",
    "-Medium: 2$\n",
    "\n",
    "Toppings:\n",
    "-Caramel sausage\n",
    "-White chocolate\n",
    "-melted peanut butter\n",
    "Each topping cost 0.5$\n",
    "\n",
    "\"\"\"} ]\n",
    "\n",
    "#Creating the panel.\n",
    "pn.extension()\n",
    "\n",
    "panels = []\n",
    "\n",
    "client_prompt = pn.widgets.TextInput(value=\"Hi\", placeholder='Enter text here…')\n",
    "button_conversation = pn.widgets.Button(name=\"talk\")\n",
    "\n",
    "interactive_conversation = pn.bind(add_prompts_conversation, button_conversation)\n",
    "\n",
    "dashboard = pn.Column(\n",
    "    client_prompt,\n",
    "    pn.Row(button_conversation),\n",
    "    pn.panel(interactive_conversation, loading_indicator=True),\n",
    ")\n",
    "\n",
    "#To talk with the chat push the botton: 'talk' after your sentence.\n",
    "dashboard"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "include_colab_link": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
